import { Ability, UIAbility, AbilityConstant, Want, common } from '@kit.AbilityKit';

/**
 * 路由记录装饰器工厂，用于配置页面的路由信息
 */

namespace Router {

  /**
   * 挂载Router
   * @param options 增强选项
   * @returns ClassDecorator
   */
  export const MountRouter = function (): ClassDecorator {
    return (target: Object) => {
      if (target && target instanceof Function && isAbility(target)) {
        let oldOnCreate = target.prototype.onCreate
        target.prototype.onCreate = function (want: Want, launchParam: AbilityConstant.LaunchParam): void {
          Router.initMap(target.name)
          oldOnCreate && oldOnCreate.apply(this, [want, launchParam])
        }
        let oldOnDestroy = target.prototype.onDestroy
        target.prototype.onDestroy = function (): void {
          // VarStorage.onDestroy()
          oldOnDestroy && oldOnDestroy.apply(this, [])
        }
      }
    }
  }

  /**
   * 路由记录装饰器工厂，用于配置页面的路由信息
   * @param options 路由记录选项
   * @returns ClassDecorator
   */
  export const RouteDecorator = function (): ClassDecorator {
    return (_target: Object) => {
    }
  }

  /**
   * 初始化路由组件
   * @param context 上下文
   * @param options 路由选项
   */
  export function initMap(abilityName: string): void {
    // let vs = VarStorage.getInstance()
    // if (vs.context) {
    //   return
    // }
    // vs.context = context
    // vs.routingOptions = options || {}
    // vs.routingOptions.rewriteMode = vs.routingOptions.rewriteMode || RewriteMode.Auto
    // vs.pageManaged = options?.pageManaged
    // tryInit()
  }

  function isAbility(target: Object): boolean {
    if (!target || !(target instanceof Function)) {
      return false
    }
    return Object.getPrototypeOf(target)?.name === 'Ability' ||
    target.isPrototypeOf(UIAbility) || target.isPrototypeOf(Ability)
  }

}

export const Route = Router.RouteDecorator
export const MountRouter = Router.MountRouter()
export default Router